/*

Copyright (c) 2016, Stefan Cloudt

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

use std::ptr;
use std::alloc::{self, Layout};
use std::mem;
use std::time::{self, Instant};

const TEST_SIZE: usize = 20;
const TEST_ARRAY: [i32; TEST_SIZE] = [10, 12, 12, 1, 2, 3, 6, 7, 2, 23, 13, 23, 23, 34, 31, 9, 21, -2, -12, -4];
const TEST_REMOVE_EL: usize = 15;
const TEST_REMOVE_RANGE: usize = 7;
const TEST_REMOVE_RANGE_LENGTH: usize = 4;

struct SortedArray {
    data: *mut i32,
    length: usize,
    capacity: usize,
    compare_func: fn(i32, i32) -> i32,
    equal_func: fn(i32, i32) -> bool,
}

impl SortedArray {
    fn new(capacity: usize, equal_func: fn(i32, i32) -> bool, compare_func: fn(i32, i32) -> i32) -> *mut SortedArray {
        let layout = Layout::new::<SortedArray>();
        let array_ptr = unsafe { alloc::alloc(layout) as *mut SortedArray };
        if array_ptr.is_null() {
            return ptr::null_mut();
        }
        unsafe {
            ptr::write(array_ptr, SortedArray {
                data: ptr::null_mut(),
                length: 0,
                capacity: capacity,
                compare_func,
                equal_func,
            });
        }
        array_ptr
    }

    fn free(&mut self) {
        unsafe {
            if !self.data.is_null() {
                alloc::dealloc(self.data as *mut u8, Layout::array::<i32>(self.capacity).unwrap());
            }
            alloc::dealloc(self as *mut SortedArray as *mut u8, Layout::new::<SortedArray>());
        }
    }

    fn insert(&mut self, value: i32) {
        if self.length >= self.capacity {
            self.capacity = self.capacity.checked_mul(2).unwrap_or(0);
            let new_layout = Layout::array::<i32>(self.capacity).unwrap();
            let new_data = unsafe { alloc::realloc(self.data as *mut u8, Layout::array::<i32>(self.length).unwrap(), new_layout.size()) as *mut i32 };
            if new_data.is_null() {
                panic!("Failed to allocate memory");
            }
            self.data = new_data;
        }
        let pos = self.length..self.length + 1;
        unsafe {
            ptr::copy(self.data.add(pos.start), self.data.add(pos.start + 1), self.length - pos.start);
            *self.data.add(pos.start) = value;
        }
        self.length += 1;
    }

    fn remove(&mut self, index: usize) {
        if index >= self.length {
            panic!("Index out of bounds");
        }
        let pos = index..index + 1;
        unsafe {
            ptr::copy(self.data.add(pos.start + 1), self.data.add(pos.start), self.length - pos.start - 1);
        }
        self.length -= 1;
    }

    fn remove_range(&mut self, start: usize, length: usize) {
        if start + length > self.length {
            panic!("Range out of bounds");
        }
        let pos = start..start + length;
        unsafe {
            ptr::copy(self.data.add(pos.start + length), self.data.add(pos.start), self.length - pos.start - length);
        }
        self.length -= length;
    }

    fn get(&self, index: usize) -> i32 {
        if index >= self.length {
            panic!("Index out of bounds");
        }
        unsafe { *self.data.add(index) }
    }

    fn index_of(&self, value: i32) -> isize {
        for i in 0..self.length {
            if (self.equal_func)(self.get(i), value) {
                return i as isize;
            }
        }
        -1
    }

    fn length(&self) -> usize {
        self.length
    }
}

fn int_compare(a: i32, b: i32) -> i32 {
    a.cmp(&b) as i32
}

fn int_equal(a: i32, b: i32) -> bool {
    a == b
}

fn check_sorted_prop(sortedarray: *mut SortedArray) {
    let array = unsafe { &*sortedarray };
    for i in 1..array.length() {
        assert!(int_compare(array.get(i - 1), array.get(i)) <= 0);
    }
}

fn free_sorted_ints(sortedarray: *mut SortedArray) {
    let array = unsafe { &mut *sortedarray };
    array.free();
}

fn generate_sortedarray_equ(equ_func: fn(i32, i32) -> bool) -> *mut SortedArray {
    let sortedarray = SortedArray::new(0, equ_func, int_compare);
    if sortedarray.is_null() {
        return ptr::null_mut();
    }
    let array = unsafe { &mut *sortedarray };
    for &item in &TEST_ARRAY {
        array.insert(item);
    }
    sortedarray
}

fn generate_sortedarray() -> *mut SortedArray {
    generate_sortedarray_equ(int_equal)
}

fn test_sortedarray_new_free() {
    let sortedarray = SortedArray::new(0, int_equal, int_compare);
    assert!(!sortedarray.is_null());
    unsafe { (*sortedarray).free() };

    let _ = SortedArray::new(0, int_equal, int_compare);
}

fn test_sortedarray_insert() {
    let sortedarray = generate_sortedarray();
    let array = unsafe { &mut *sortedarray };
    let mut rng = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap().as_nanos();
    for _ in 0..20 {
        let i = (rng % 100) as i32;
        rng /= 2;
        array.insert(i);
    }
    check_sorted_prop(sortedarray);
    free_sorted_ints(sortedarray);
}

fn test_sortedarray_remove() {
    let sortedarray = generate_sortedarray();
    let array = unsafe { &mut *sortedarray };
    let ip = array.get(TEST_REMOVE_EL + 1);
    array.remove(TEST_REMOVE_EL);
    assert_eq!(array.get(TEST_REMOVE_EL), ip);
    check_sorted_prop(sortedarray);
    free_sorted_ints(sortedarray);
}

fn test_sortedarray_remove_range() {
    let sortedarray = generate_sortedarray();
    let array = unsafe { &mut *sortedarray };
    let mut new = [0; TEST_REMOVE_RANGE_LENGTH];
    for i in 0..TEST_REMOVE_RANGE_LENGTH {
        new[i] = array.get(TEST_REMOVE_RANGE + TEST_REMOVE_RANGE_LENGTH + i);
    }
    array.remove_range(TEST_REMOVE_RANGE, TEST_REMOVE_RANGE_LENGTH);
    for i in 0..TEST_REMOVE_RANGE_LENGTH {
        assert_eq!(array.get(TEST_REMOVE_RANGE + i), new[i]);
    }
    check_sorted_prop(sortedarray);
    free_sorted_ints(sortedarray);
}

fn test_sortedarray_index_of() {
    let sortedarray = generate_sortedarray();
    let array = unsafe { &*sortedarray };
    for i in 0..TEST_SIZE {
        let r = array.index_of(array.get(i));
        assert!(r >= 0);
        assert_eq!(array.get(r as usize), array.get(i));
    }
    free_sorted_ints(sortedarray);
}

fn ptr_equal(v1: i32, v2: i32) -> bool {
    v1 == v2
}

fn test_sortedarray_index_of_equ_key() {
    let sortedarray = generate_sortedarray_equ(ptr_equal);
    let array = unsafe { &*sortedarray };
    for i in 0..TEST_SIZE {
        let r = array.index_of(array.get(i));
        assert!(r >= 0);
        assert_eq!(i, r as usize);
    }
    free_sorted_ints(sortedarray);
}

fn test_sortedarray_get() {
    let sortedarray = generate_sortedarray();
    let array = unsafe { &*sortedarray };
    for i in 0..array.length() {
        assert_eq!(array.get(i), array.get(i));
    }
    free_sorted_ints(sortedarray);
}

type UnitTestFunction = fn();

fn run_tests(tests: &[UnitTestFunction]) {
    for &test in tests {
        test();
    }
}

fn main() {
    let tests: [UnitTestFunction; 7] = [
        test_sortedarray_new_free,
        test_sortedarray_insert,
        test_sortedarray_remove,
        test_sortedarray_remove_range,
        test_sortedarray_index_of,
        test_sortedarray_index_of_equ_key,
        test_sortedarray_get,
    ];
    run_tests(&tests);
}